package Linklist.linklist.one;
// 1、无头单向非循环链表实现
public class Linklist {
    static class linknode{
        public int val;
        public linknode next;
        public linknode(int val){
            this.val=val;
        }
    }
    public linknode head;
    public void createList(){
        linknode node1=new linknode(12);
        linknode node2=new linknode(12);
        linknode node3=new linknode(14);
        linknode node4=new linknode(15);
        linknode node5=new linknode(16);
        linknode node6=new linknode(17);
        node1.next=node2;
        node2.next=node3;
        node3.next=node4;
        node4.next=node5;
        node5.next=node6;

        this.head=node1;
    }


    //头插法
    public void addFirst(int data){
        linknode node=new linknode(data);
        node.next=head;
        this.head=node;
    }
    //尾插法
    public void addLast(int data){
        linknode cur=head;
        linknode node=new linknode(data);
        while (cur.next!=null){
            cur=cur.next;
        }
        cur.next=node;
    }
    //任意位置插入,第一个数据节点为0号下标
    public void addIndex(int index,int data){
        linknode cur=head;
        linknode node=new linknode(data);
        if (index==0){
            addFirst(data);
            return;
        }
        if (index==size()){
            addLast(data);
            return;
        }
        for (int i = 0; i <index-1; i++) {
            cur=cur.next;
        }
        node.next=cur.next;
        cur.next=node;
    }
    //查找是否包含关键字key是否在单链表当中
    public boolean contains(int key){
        linknode cur=head;
        while (cur.next!=null){
            if (cur.val==key){
                return true;
            }
            cur=cur.next;
        }
        return false;
    }
    //删除第一次出现关键字为key的节点
    public void remove(int key){
        linknode cur=head;
        if (head.val==key){
            head=head.next;
            return;
        }
        while (cur.next!=null){
            if(cur.next.val==key){
                cur.next=cur.next.next;
                return;
            }
            cur=cur.next;
        }
    }
    //删除所有值为key的节点
    public void removeAllKey(int key){
        linknode cur=head;
        linknode prve=head;
        while (cur!=null){
            if (cur.val==key){
                prve.next=cur.next;
                cur=cur.next;
            }else {
                prve=cur;
                cur=cur.next;
            }
        }
        if(head.val==key){
            head=head.next;
        }
    }
    //得到单链表的长度
    public int size(){
        int size=1;
        linknode cur=head;
        while (cur.next!=null){
            cur=cur.next;
            size++;
        }
        return size;
    }
    public void clear() {
        this.head=null;
    }
    public void display() {
        linknode cur=head;
        while (cur!=null){
            System.out.print(cur.val+" ");
            cur=cur.next;
        }
    }
}
